package com.luyou.a03;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 *  spring 使用的是模版方法
 *  Bean 生命周期的各个阶段进行拓展的 BeanPostProcessor(后置处理器)，比如 InstantiationAwareBeanPostProcessor 和 DestructionAwareBeanPostProcessor。
 *
 * @author 28336
 * @version 1.0
 * Create by 2023/12/11 8:26
 */
@Component
public class MyBeanPostProcessor implements InstantiationAwareBeanPostProcessor, DestructionAwareBeanPostProcessor {

    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        if ("lifeCycleBean".equals(beanName)) {
            System.out.println("<<<<<<<<<< 实例化之前执行，这里返回的对象会替换掉原本的 bean");
        }
        return null;
    }




    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if ("lifeCycleBean".equals(beanName)) {
            System.out.println("<<<<<<<<<< 实例化之后执行，如果返回 false 会跳过依赖注入节点");
//             return false;
        }
        return true;
    }

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        if ("lifeCycleBean".equals(beanName)) {
            System.out.println("<<<<<<<<<< 依赖注入阶段执行，如 @Autowired、@Value、@Resource");
        }
        return pvs;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if ("lifeCycleBean".equals(beanName)) {
            System.out.println("<<<<<<<<<< 初始化执行之前，这里返回的对象会替换掉原本的 bean，如 @PostConstruct、@ConfigurationProperties");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if ("lifeCycleBean".equals(beanName)) {
            System.out.println("<<<<<<<<<< 初始化之后执行，这里返回的对象会替换掉原本的 bean，如代理增强");
        }
        return bean;
    }

    @Override
    public void postProcessBeforeDestruction(Object o, String beanName) throws BeansException {
        if ("lifeCycleBean".equals(beanName)) {
            System.out.println("<<<<<<<<<< 销毁执行之前，如 @PreDestroy");
        }
    }
}
